package ua.edu.nuos.jeetraining2012.cms.util.mail;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.List;

@Stateless
public class Mail {

    @Resource(name = "mail/default")
    protected Session mailSession;

    final private static Logger logger = LoggerFactory.getLogger(Mail.class);


    private void addRecipients(List<InternetAddress> list, Message.RecipientType type, Message msg) throws MessagingException {
        for (InternetAddress address : list) {
            msg.addRecipient(type, address);
        }
    }

    public void send(Sendable envelopment) {
        MimeMessage msg = new MimeMessage(mailSession);
        try {
            msg.setSubject(envelopment.getSubject(), "UTF-8");
            addRecipients(envelopment.getRecipientList(), Message.RecipientType.TO, msg);
            addRecipients(envelopment.getCCList(), Message.RecipientType.CC, msg);
            addRecipients(envelopment.getCCList(), Message.RecipientType.BCC, msg);

            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent(envelopment.getBodyMessage(),"text/html; charset=UTF-8");
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            msg.setContent(multipart,"text/plain; charset=UTF-8");
            Transport.send(msg);
            logger.debug("Mail sent");
        } catch (MessagingException e) {
            logger.error("Can't send mail", e);
        }
    }
}
